package com.example.wxback.controller;

import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.toolkit.ObjectUtils;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.example.wxback.model.ActivationCodePo;
import com.example.wxback.service.ActivationCodeService;
import com.example.wxback.session.SessionUserInfo;
import com.example.wxback.util.CommandTools;
import com.example.wxback.util.CommonUtil;
import com.example.wxback.util.DateUtil;
import com.example.wxback.util.ShareCodeUtil;
import org.apache.ibatis.annotations.Param;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

@RestController
@RequestMapping("/wx/code")
public class ActivationCodeController {

    @Autowired
    private ActivationCodeService activationCodeService;

    @GetMapping("/codes")
    public JSONObject getCodes(@Param("pageNum") int pageNum,
                               @Param("pageRow") int pageRow,
                               @Param("code") String code,
                               @Param("phone") String phone,
                               @Param("expiredType") String expiredType,
                               @Param("type") String type,
                               HttpServletRequest request) {
        SessionUserInfo sessionUserInfo = (SessionUserInfo) request.getAttribute("users");
        if (sessionUserInfo == null) {
            return CommonUtil.errorJson("管理员不存在");
        }
        if (!CommandTools.isAdmin(sessionUserInfo.getMemberType())) {
            return CommonUtil.errorJson("非管理员禁止操作");
        }
        if (pageNum < 0) {
            return CommonUtil.errorJson("参数不合法");
        } else if (pageRow < 0) {
            return CommonUtil.errorJson("参数不合法");
        }
        if (StringUtils.endsWith(type, "0")) {
            type = "";
        }

        JSONObject jsonObject = new JSONObject();
        jsonObject.put("offSet", (pageNum - 1) * pageRow);
        jsonObject.put("pageSize", pageRow);
        jsonObject.put("code", code);
        jsonObject.put("phone", phone);
        jsonObject.put("type", type);
        if ("0".equals(expiredType)) {
            jsonObject.put("expiredType", "");
        } else {
            jsonObject.put("expiredType", expiredType);
        }

        jsonObject.put("currentTime", DateUtil.getCurrentTime());
        int total = activationCodeService.countList(jsonObject);
        List<JSONObject> list = activationCodeService.findList(jsonObject);
        return CommonUtil.successPageWithJSONObject(pageRow, list, total);
    }

    @PostMapping
    public JSONObject insert(@RequestBody JSONObject requestJson, HttpServletRequest request) {
        SessionUserInfo sessionUserInfo = (SessionUserInfo) request.getAttribute("users");
        if (sessionUserInfo == null) {
            return CommonUtil.errorJson("管理员不存在");
        }
        if (!CommandTools.isAdmin(sessionUserInfo.getMemberType())) {
            return CommonUtil.errorJson("非管理员禁止操作");
        }
        CommonUtil.hasAllRequired(requestJson, "type,count");
        int count = requestJson.getIntValue("count");

        boolean flag = false;
        for (int i = 0; i < count; i++) {
            String randomCode = ShareCodeUtil.genRandomNum();
            ActivationCodePo activationCodePo = new ActivationCodePo();
            activationCodePo.setCreateTime(new Date());
            activationCodePo.setType(requestJson.getIntValue("type"));
            activationCodePo.setCode(randomCode);
            flag = activationCodeService.insert(activationCodePo);
        }
        if (flag) {
            return CommonUtil.successJson("操作成功");
        } else {
            return CommonUtil.errorJson("创建失败");
        }
    }

    @DeleteMapping("/{id}")
    public JSONObject delete(@PathVariable("id") String id, HttpServletRequest request) {
        SessionUserInfo sessionUserInfo = (SessionUserInfo) request.getAttribute("users");
        if (sessionUserInfo == null) {
            return CommonUtil.errorJson("管理员不存在");
        }
        if (!CommandTools.isAdmin(sessionUserInfo.getMemberType())) {
            return CommonUtil.errorJson("非管理员禁止操作");
        }
        ActivationCodePo activationCodePo = activationCodeService.selectById(id);
        if (activationCodePo == null) {
            return CommonUtil.errorJson("未找到指定激活码");
        } else if (activationCodePo.getExpirationTime() != null
                && DateUtil.getTimeFromDate(activationCodePo.getExpirationTime()).compareTo(DateUtil.getCurrentTime()) > 0) {
            return CommonUtil.errorJson("激活码未过期，禁止删除");
        }
        if (activationCodeService.deleteById(id) > 0) {
            return CommonUtil.successJson("删除成功");
        } else {
            return CommonUtil.errorJson("删除失败");
        }
    }

    @DeleteMapping("/codes")
    public JSONObject deleteMulityCodes(@RequestBody JSONObject requestJson, HttpServletRequest request) {
        SessionUserInfo sessionUserInfo = (SessionUserInfo) request.getAttribute("users");
        if (sessionUserInfo == null) {
            return CommonUtil.errorJson("管理员不存在");
        }
        if (!CommandTools.isAdmin(sessionUserInfo.getMemberType())) {
            return CommonUtil.errorJson("非管理员禁止操作");
        }
        CommonUtil.hasAllRequired(requestJson, "codes");
        String codes = requestJson.getString("codes");
        String[] codesArr = codes.split(",");
        if (ObjectUtils.isEmpty(codesArr)) {
            return CommonUtil.errorJson("删除数据不能为空");
        }
        int len = codesArr.length;
        List<String> list = new ArrayList<>();
        for (int i = 0; i < len; i++) {
            list.add(codesArr[i]);
        }
        if (activationCodeService.deleteMulityCodes(list) > 0) {
            return CommonUtil.successJson("删除成功");
        } else {
            return CommonUtil.successJson("删除失败,未找到需要删除的数据");
        }
    }
}
